/*
 * On remote call error
 */
function showError(msg) {
	if (msg.indexOf("SYSTEM INTERNAL ERROR") < 0) {
		alert(msg);
		return;
	}
	if (!$('feedback_link')) {
		alert(msg + "You may call support team for help.");
		return;
	}
	if (confirm(msg + "Do you want to report this error to support team?"))
		setTimeout("$('feedback_link').fireEvent('onclick')", 300);
}


/*
 * NL number format
 */
var NLFormat = function(numGroupChar, numDecimalChar, minFraction, maxFraction) {
	this.gc = numGroupChar;
	this.dc = numDecimalChar;
	this.minf = (minFraction) ? minFraction : 2;
	this.maxf = (maxFraction) ? maxFraction : 3;
	this.regexMarkDc = new RegExp("[" + this.dc + "]");
	this.regexRmTz = new RegExp("0{0," + (this.maxf-this.minf) + "}$");
}

NLFormat.prototype = {
	
	parseFloat: function(s) {
		return parseFloat(this._stdFloat(s), 10);
	},
	
	parseInt: function(s) {
		if(typeof s == 'number')
			return s;
		if(s == null || s.length == 0) {
			return 0;
		}
		return parseInt(this._stdInt(s), 10);
	},
	
	formatFloat: function(f) {
		var s = f.toFixed(this.maxf).replace(this.regexRmTz, '');
		return this._addGc(this._stdFloat(s).replace(/[.]/, this.dc));
	},
	
	formatInt: function(i) {
		return this._addGc(i.toFixed(0));
	},
	
	_stdFloat: function(s) {
		return s.replace(this.regexMarkDc, '__').replace(/[., ']/g, '').replace(/__/, '.');
	},
	
	_stdInt: function(s) {
		return s.replace(this.regexMarkDc, '__').replace(/__\d*/, '').replace(/[., ']/g, '');
	},
	
	_addGc: function(s) {
		var x = s.split(this.dc);
		var x1 = x[0];
		var x2 = x.length > 1 ? this.dc + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + this.gc + '$2');
		}
		return x1 + x2;
	}
}

// US format
var usf = new NLFormat(',', '.');



/*
 * Flash message
 */
var FlashMsg = {
	show: function(msgHtml) {
		FlashMsg.hold();
		$('flash-msg-content').innerHTML = msgHtml;
		if (!$('flash-msg').fn) $('flash-msg').fn = jQuery($('flash-msg'));
		$('flash-msg').fn.slideDown('normal');
		FlashMsg.countDown(3);
	},
	
	countDown: function(count) {
		var m = $('flash-msg');
		if (count > 0) {
			$('flash-msg-hide').innerHTML = "hide in " + count;
			count--;
			m.timeout = window.setTimeout("FlashMsg.countDown("+count+")", 1000);
		} else {
			m.timeout = 0;
			FlashMsg.hide();
		}
	},
	
	hold: function() {
		var m = $('flash-msg');
		if (m.timeout > 0) {
			window.clearTimeout(m.timeout);
			m.timeout = 0;
			$('flash-msg-hide').innerHTML = "hide";
		}
	},
	
	hide: function() {
		FlashMsg.hold();
		Yutil.hide('flash-msg');
	}
}


/*
 * Misc
 */
function asFloat(elem) {
	var e = $(elem);
	if (!e || !e.value) return 0;
	var r = usf.parseFloat(e.value);
	return r.toString() == 'NaN' ? 0 : r;
}

function trimFloat(v) {
	var f = Math.round(v * 1000) / 1000;
	return usf.formatFloat(f);
}



function StringBuffer() {
	this.__strings__ = new Array;
}

StringBuffer.prototype.append = function (str) {
	this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
	return this.__strings__.join('');
};

/**
* Project sorting function
*/
sortAllPrjs = function(by){
	sortPrj('Standard', by);
	sortPrj('Financial', by);
	sortPrj('Trafix', by);
	sortPrj('Archived', by);
}
sortPrj = function(scope, by){
	if(!$('prjs_' + scope))
		return;
	var prjs = ('ul.tree/li.' + scope).resolve($('prjs_' + scope + '_c'));
	if (prjs.length == 0) return;
	
	if ('byIdDesc' == by) {
		prjs.sort(comp_id_desc);
	} else if('byIdAsc' == by) {
		prjs.sort(comp_id_asc);
	} else if('byTimeAsc' == by) {
		prjs.sort(comp_t_asc);
	} else if('byTimeDesc' == by) {
		prjs.sort(comp_t_desc);
	}

	var ul = prjs[0].parentNode;
	for (var i = 0; i < prjs.length; i++)
		ul.appendChild(prjs[i]);
}
comp_id_asc = function(a, b) {
	return a.getAttribute('sortId') > b.getAttribute('sortId') ? 1: -1;
}
comp_id_desc = function(a, b) {
	return a.getAttribute('sortId') < b.getAttribute('sortId') ? 1: -1;
}
comp_t_asc = function (a, b) {
	return a.getAttribute('sortDate') > b.getAttribute('sortDate') ? 1: -1;
}
comp_t_desc = function(a, b) {
	return a.getAttribute('sortDate') < b.getAttribute('sortDate') ? 1: -1;
}

/**
* DWC Utils
*/
var DwcUtil ={	
	compareDates: function(dt1, dt2){
		try {
			if(!(dt1 instanceof Date)){
				dt1 = parseDateString(dt1);
			}
			if(!(dt2 instanceof Date)){
				dt2 = parseDateString(dt2);
			}
			
			dt1 = dt1.getFullYear() * 1000 + (dt1.getMonth()+1) * 100 + dt1.getDate();
			dt2 = dt2.getFullYear() * 1000 + (dt2.getMonth()+1) * 100 + dt2.getDate();
			return dt1 - dt2;
		} catch (e) {
			alert("Please input a date in valid form 'YYYY-MM-DD'");
			return;
		}
	},
	
	compareWithToday: function(dt1){
		return this.compareDates(dt1, new Date());
	},
	
	isChildOf: function(child, dad){
		if(!child || !dad)
			return false;
		
		var p = child.parentNode;
		while(p){
			if(p == dad)
				return true;
			p = p.parentNode;
		}
		
		return false;
	},
	
	hasParentClass: function(child, clazz){
		if(!child || !clazz)
			return false;
		
		if(clazz.hasClass(child))
			return true;
		var p = child.parentNode;
		while(p){
			if(clazz.hasClass(p))
				return true;
			p = p.parentNode;
		}
		
		return false;
	},
	
	fixIEHoverIssue: function(elem){
		// to let hover popup from 'content_left' fully visible in IE (walk around stupid IE bug)
		if(!elem)
			return;
		if (Yutil.isIE) {
			elem.style.position = 'relative';
			elem.style.zIndex = '1';
			elem.style.overflow = 'visible';
		}
	}
}

Array.prototype.contains = function (elem){
	var map = {};
	for(var i=0; i<this.length; i++){
		map[this[i]] = '';
	}
	return elem in map;
};

Array.prototype.remove=function(str){
	for(var i=0; i<this.length; i++){
		if(str == this[i]){
			this.splice(i, 1);
		}
	}
};

/**
* In charge of remembering the unfolded elements on left-nav, so that when the left-nav is re-rendered,
* the fold/unfold status can be recovered on left-nav.
**/
var NodeRem = {
	add: function(elem){
		NodeRem.scroll = $('left-nav-middle').scrollTop;
		if(!elem || !elem.id)
			return;

		var modId = elem.id.substring(0, 7) + '_pt';
		var shipsId = elem.id.substring(0, 5) + '_ships_pt';
		if(elem.id.indexOf("_") ==11){
			if(!NodeRem.nodes.contains(modId)){
				//For IU elems, push module ID
				NodeRem.nodes.push(modId);
			}
			return;
		}

		if(elem.id.indexOf("_pt") == 9 && elem.id.indexOf("#") == -1){
			if(!NodeRem.nodes.contains(shipsId)){
				//For ship elems, push c2id_ships_pt
				NodeRem.nodes.push(shipsId);
			}
			return;
		}

		if(!NodeRem.nodes.contains(elem.id)){
			NodeRem.nodes.push(elem.id);
		}
		
	},
	
	remove: function(elem){
		if(!elem || !elem.id)
			return;
		NodeRem.nodes.remove(elem.id);
	},
	
	removeTree: function(elem){
		if(!elem || !elem.id)
			return;
	
		var suffixLen = '_pt'.length;
		var root = elem.id.substring(0, elem.id.length-suffixLen);
		var result = new Array();

		for(var i=0, n=NodeRem.nodes.length; i<n; i++){
			var node = NodeRem.nodes[i];
			if(node && node.indexOf(root)==-1){
				result.push(node);
			}
		}
        NodeRem.nodes = result;
	}
}
NodeRem.nodes = new Array();
NodeRem.scroll = 0;

/**
* Keep the current focus of left-nav highlighted
**/
var FocusMgr ={
	setFocus: function(elem){
		if(!elem){
			return;
		}
		if( $(FocusMgr.curFocus)){
			if ('currentFocus'.hasClass($(FocusMgr.curFocus)))
				'currentFocus'.removeClass($(FocusMgr.curFocus));
		}
		FocusMgr.curFocus = elem.id;
		'currentFocus'.addClass(elem);
	}
}
FocusMgr.curFocus = null;

